<!-- 轮播图/视频 -->
<template>
  <div>
    <el-upload ref="upload" :class="{ showUpLoad: disabled || fileList.length == limit }" action="#" :show-file-list="false" :limit="limit" :file-list="fileList" :on-change="onChange" :on-success="onSuccess" :on-preview="handlePictureCardPreview" :accept="accept" :on-exceed="onExceed" :auto-upload="false" :disabled="disabled">
      <div v-if="accept === '.doc, .docx, .pdf, .xls, .xlsx, .txt' && !disabled" slot="tip" class="el-upload__tip">可上传多种pdf,xls,doc文件</div>
      <el-button v-if="!disabled" size="small" type="primary">点击上传</el-button>
    </el-upload>
    <div class="preview">
      <div v-for="(item, index) in fileList" :key="index" class="list-item">
        <i class="el-icon-tickets icon"></i>
        <p @click="view(item)">{{ item.name }}</p>
        <div class="todo">
          <i class="el-icon-close icon" @click="onRemove(item)"></i>
        </div>
      </div>
    </div>
    <!-- 预览 -->
    <el-dialog title="预览" :visible.sync="dialogVisible" append-to-body top="0">
      <!-- <iframe v-if="dialogFilelName.includes('.pdf') || dialogFilelName.includes('.txt')" id="iframe" class="iframe" :src="page_url" frameborder="0" width="100%"></iframe> -->
      <iframe id="iframe" class="iframe" :src="'https://view.officeapps.live.com/op/view.aspx?src=' + dialogFile" controls muted width="100%"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import DocumentApi from '@/api/document';
import baseUrl from '@/api/baseURL';
import axios from 'axios';
export default {
  name: 'UploadDocument',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: Array,
      default: () => []
    },
    accept: {
      type: String,
      default: 'jpg/mp4'
    },
    limit: {
      type: Number,
      default: 9
    },
    fileList: {
      type: Array,
      default: () => []
    },
    moduleType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false, // 图片弹窗
      dialogFile: '', // 预览图片
      dialogFilelName: '', // 预览图片
      page_url: '',
      dialogViewVideo: false, // 视频弹窗
      dialogVideo: '', // 预览视频
      loading: true // 加载效果
    };
  },
  computed: {},
  methods: {
    onChange(file, fileList) {
      const a = [];
      fileList.forEach(res => {
        if (res.fileType) {
          a.push(res); // 获取带有res.fileType的结构（和fileList相比少了最后一个添加的数据），表示新加之前的数据；
        }
      });
      //
      this.loading = true;
      const dataForm = new FormData();
      dataForm.append('file', file.raw);
      dataForm.append('moduleType', this.moduleType);
      dataForm.append('upDownType', 'FTP');
      if (file.raw.type === 'application/pdf' || file.raw.type === 'application/msword' || file.raw.type === 'application/vnd.ms-excel' || file.raw.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        DocumentApi.upload(dataForm)
          .then(res => {
            fileList[fileList.length - 1].fileType = file.raw.type;
            fileList[fileList.length - 1].fileId = res.data.fileId;
            fileList[fileList.length - 1].url = `${baseUrl.fileUrl}moduleType=${this.moduleType}&fileId=${res.data.fileId}`;
            this.$emit('input', {
              list: JSON.parse(JSON.stringify(fileList)),
              obj: {
                fileType: file.raw.type,
                fileName: res.data.fileName,
                fileId: res.data.fileId,
                res: res.data
              }
            });
            this.$emit('reset');
            this.loading = false;
          })
          .catch(() => {
            fileList.splice(-1, 1);
            this.$message.error('上传失败！');
          });
      } else {
        this.$message.error('pdf,doc,xls,txt类型的文件');
        fileList.splice(-1, 1);
        return;
      }
    },
    onRemove(file) {
      this.$emit('delectFileId', file);
    },
    // 文件超出个数限制时
    onExceed(file) {
      this.$message.info(`最多上传${this.limit}张`);
    },
    // loading设置
    onSuccess(response, file, fileList) {},
    // 预览
    view(file) {
      console.log(file);
      this.dialogFile = file.url;
      this.dialogFilelName = file.name;
      this.dialogVisible = true;
    },
    makePdf(url) {
      // 把孙悟空替换为了猪八戒
      var newstr = url.replace(/%26/g, '&');
      //  console.log(newstr);
      axios.get(newstr, { responseType: 'blob' }).then(res => {
        const { data } = res;
        let binaryData = [];
        binaryData.push(data); // res 后台返回的流数据
        let pdfUrl = '';
        pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
        this.page_url = pdfUrl;
        this.dialogVisible = true;
      });
    },
    handlePictureCardPreview(file) {},
    // 清空
    clearFiles() {
      this.$refs.upload.clearFiles();
    }
  }
};
</script>

<style scoped lang="scss">
.preview {
  margin-top: 10px;
  .list-item {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    padding-right: 10px;
    box-sizing: border-box;
    &:hover {
      .todo {
        display: block;
      }
    }
    &:last-of-type {
      margin-bottom: 0;
    }
    p {
      line-height: normal;
      padding: 0;
      margin: 0;
      flex: 1;
      padding: 0 10px;
      box-sizing: border-box;
      overflow: hidden; /* 隐藏超出div容器部分 */
      text-overflow: ellipsis; /* 溢出部分文本显示省略号 */
      white-space: nowrap;
      cursor: pointer;
      &:hover {
        color: #409eff;
      }
    }
    .todo {
      line-height: normal;
      display: none;
      > * {
        cursor: pointer;
        &:hover {
          color: #000;
        }
      }
    }
  }
}
.iframe {
  height: 80vh;
}
</style>
